package fun.linze.wallpaperwebsite.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import fun.linze.wallpaperwebsite.dao.wallpaper.Tags;
import fun.linze.wallpaperwebsite.dao.wallpaper.WallpaperPutDAO;
import fun.linze.wallpaperwebsite.dao.wallpaper.WallpaperUploadDAO;
import fun.linze.wallpaperwebsite.dao.user.UserInfoDAO;
import fun.linze.wallpaperwebsite.domain.TTag;
import fun.linze.wallpaperwebsite.domain.TWallpaper;
import fun.linze.wallpaperwebsite.domain.TWallpaperTag;
import fun.linze.wallpaperwebsite.service.TUserService;
import fun.linze.wallpaperwebsite.service.TWallpaperService;
import fun.linze.wallpaperwebsite.mapper.TWallpaperMapper;
import fun.linze.wallpaperwebsite.util.JwtUtil;
import fun.linze.wallpaperwebsite.util.ListSetUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.stream.Stream;

/**
* @author wangy
* @description 针对表【t_wallpaper(壁纸信息表)】的数据库操作Service实现
* @createDate 2025-06-27 18:02:42
*/
@Service
public class TWallpaperServiceImpl extends ServiceImpl<TWallpaperMapper, TWallpaper>
    implements TWallpaperService{

    @Autowired
    TUserServiceImpl tUserServiceImpl;
    @Autowired
    TWallpaperTagServiceImpl tWallpaperTagServiceImpl;
    @Autowired
    TTagServiceImpl tTagServiceImpl;

    @Value("${wallpaper.upload.dir}")
    private String uploadDir;

    @Override
    public ResponseEntity<?> uploadWallpaper( WallpaperUploadDAO wallpaperUploadDAO, String authHeader) {
        // 在本地文件系统检查文件是否已经存在（存在即可上传，不存在说明用户乱调接口）
        if (!StringUtils.hasText(wallpaperUploadDAO.getFileName())) {
            return ResponseEntity.badRequest().body("文件名不能为空");
        }
        System.out.println("令牌"+authHeader+"\n"+"令牌获取的用户名"+tUserServiceImpl.getUsernameFromToken(authHeader));



        String fileName = wallpaperUploadDAO.getFileName();
        File file = Paths.get(uploadDir, fileName).toFile();
        if (!file.exists()) {
            return ResponseEntity.badRequest().body("文件不存在，禁止上传");
        }

        //将文件信息存入数据库
        TWallpaper wallpaper = new TWallpaper();
        wallpaper.setTitle(wallpaperUploadDAO.getTitle());
        wallpaper.setDescription(wallpaperUploadDAO.getDescription());
        wallpaper.setFileUrl(wallpaperUploadDAO.getFileName());
        UserInfoDAO uploader = tUserServiceImpl.getUserInfo(JwtUtil.getUsernameFromToken(authHeader));
        if (uploader == null) {
            return ResponseEntity.status(401).body("无效的令牌，用户不存在");
        }
        wallpaper.setUploaderId(uploader.getId());
        wallpaper.setStatus(0);// 默认状态为0（待审核）

        boolean saved = this.save(wallpaper);
        //获取壁纸ID
        if (saved) {
            System.out.println("壁纸上传成功，ID: " + wallpaper.getId());
        }
        if (saved) {
            return ResponseEntity.ok("壁纸上传成功");
        } else {
            return ResponseEntity.status(500).body("壁纸上传失败");
        }
    }

    @Override
/**
 * 获取壁���列表
 * @param page 页码
 * @param size 每页数量
 * @param sort 排序方式（"new"表示按创建时间倒序，"hot"表示按下载量倒序）
 * @param tags 标签数组（后续会添加标签过滤逻辑）
 * @return 壁纸分页结果
 */
    public ResponseEntity<?> getWallpapers(int page, int size, String sort, String[] tags) {
        Page<TWallpaper> pager = new Page<>(page, size);
        QueryWrapper<TWallpaper> queryWrapper = new QueryWrapper<>();

        // 只查已发布
//        queryWrapper.eq("status", 1);

        // 排序
        if ("new".equals(sort)) {
            queryWrapper.orderByDesc("created_at");
        } else if ("hot".equals(sort)) {
            queryWrapper.orderByDesc("download_count");
        } else if ("view".equals(sort)) {
            queryWrapper.orderByDesc("view_count");
        } else if ("like".equals(sort)) {
            queryWrapper.orderByDesc("like_count");
        }

//        // 标签过滤（如有标签字段或多对多关系可补充）
//        if (tags != null && tags.length > 0) {
//            // 示例：假设有tag字段
//            queryWrapper.in("tag", Arrays.asList(tags));
//        }

        Page<TWallpaper> result = this.page(pager, queryWrapper);
        return ResponseEntity.ok(result);
    }

    @Override
    public ResponseEntity<?> getWallpaperById(String id) {
        TWallpaper tWallpaper = baseMapper.selectById(id);
        if (tWallpaper == null) {
            return ResponseEntity.badRequest().body("<UNK>");
        }
        //添加壁纸浏览数
        tWallpaper.setViewCount(tWallpaper.getViewCount() + 1);
        this.updateById(tWallpaper);
        return ResponseEntity.ok(tWallpaper);
    }

    @Override
    public ResponseEntity<?> putWallpaperById(String id, WallpaperPutDAO wallpaperPutDAO) {
        //根据id更新壁纸的title和description
        TWallpaper tWallpaper = baseMapper.selectById(id);
        if (tWallpaper == null) {
            return ResponseEntity.badRequest().body("<UNK>");
        }
        tWallpaper.setTitle(wallpaperPutDAO.getTitle());
        tWallpaper.setDescription(wallpaperPutDAO.getDescription());
        //将新的tWallpaper存放在数据库中
        this.updateById(tWallpaper);
        return ResponseEntity.ok(tWallpaper);
    }

    @Override
    public void LikeWallpaper(String id) {
        TWallpaper tWallpaper = baseMapper.selectById(id);
        tWallpaper.setLikeCount(tWallpaper.getLikeCount() + 1);
        this.updateById(tWallpaper);
    }

    @Override
    public void DownloadWallpaper(String id) {
        TWallpaper tWallpaper = baseMapper.selectById(id);
        tWallpaper.setDownloadCount(tWallpaper.getDownloadCount() + 1);
        this.updateById(tWallpaper);
    }

    @Override
    public void AddWallpaperTags(Long id, Tags tags) {

        //标签预处理
        //获取此壁纸id的所有标签id
        List<Integer> tagId = tWallpaperTagServiceImpl.getTagIdsByWallpaperId(id);
        //根据标签id获取对应的标签名称
        List<String> tag=tTagServiceImpl.getTagNameById(tagId);

        //自定义util计算tag的对称差集
        List<String> inTag=tags.getTags();
        List<String> newTags= ListSetUtils.getSymmetricDifference(tag,inTag);



        //如果newTags不为空，说明有新的标签需要添加
        if (!newTags.isEmpty()) {
            //遍历newTags，添加到tag表中
            for (String tagName : newTags) {
                //检查tag表中是否已经存在此标签
                QueryWrapper<TTag> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("name", tagName);
                TTag existingTag = tTagServiceImpl.getOne(queryWrapper);

                if (existingTag == null) {
                    //果不存在，则创建新的标签
                    TTag newTag = new TTag();
                    newTag.setName(tagName);
                    tTagServiceImpl.save(newTag);
                    //将新标签的id添加到tagId列表中
                    tagId.add(newTag.getId());
                } else {
                    //如果存在，则直接使用已有的标签id
                    tagId.add(existingTag.getId());
                }
            }
        }

        //将对称差集的标签id添加到壁纸与标签的关联表中
        for (Integer tagIdItem : tagId) {
            // 检查关联表中是否已存在此壁纸与标签的关联
            QueryWrapper<TWallpaperTag> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("wallpaper_id", id).eq("tag_id", tagIdItem);
            TWallpaperTag existingRelation = tWallpaperTagServiceImpl.getOne(queryWrapper);

            if (existingRelation == null) {
                // 如果不存在，则创建新的关联
                TWallpaperTag newRelation = new TWallpaperTag();
                newRelation.setWallpaperId(id);
                newRelation.setTagId(tagIdItem);
                tWallpaperTagServiceImpl.save(newRelation);
            }
        }

    }

    @Override
    public void RemoveWallpaperTags(Long id, Tags tags) {
        //获取此壁纸id的所有标签id
        List<Integer> tagId = tWallpaperTagServiceImpl.getTagIdsByWallpaperId(id);
        //根据标签id获取对应的标签名称
        List<String> tag=tTagServiceImpl.getTagNameById(tagId);

        //自定义util计算tag的合集
        List<String> inTag=tags.getTags();
        List<String> newTags= ListSetUtils.getUnion(tag,inTag);

        //如果newTags不为空，说明有新的标签需要删除
        if (!newTags.isEmpty()) {
            //遍历newTags，删除tag表中对应的标签
            for (String tagName : newTags) {
                //检查tag表中是否已经存在此标签
                QueryWrapper<TTag> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("name", tagName);
                TTag existingTag = tTagServiceImpl.getOne(queryWrapper);

                if (existingTag != null) {
                    //如果存在，则删除此标签
                    tTagServiceImpl.removeById(existingTag.getId());
                }
            }
        }

        //将合集的标签id从壁纸与标签的关联表中删除
        for (Integer tagIdItem : tagId) {
            // 检查关联表中是否已存在此壁纸与标签的关联
            QueryWrapper<TWallpaperTag> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("wallpaper_id", id).eq("tag_id", tagIdItem);
            long count = tWallpaperTagServiceImpl.count(queryWrapper);

            if (count > 0) {
                // 如果存在，则删除此关联
                tWallpaperTagServiceImpl.remove(queryWrapper);
            }
        }

    }
}
